package com.lv.suyiyong.hfr.ui

import android.graphics.Color
import android.os.CountDownTimer
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.lv.common.base.BaseActivity
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.filterLine
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.ktx.priceSmallDot
import com.lv.common.ktx.setSafeListener
import com.lv.common.ktx.urlAddBorder
import com.lv.common.ktx.viewLifeCycleOwner
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MoneyUtil
import com.lv.common.utils.MyUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.common.widget.tab.SlidingTabStrip
import com.lv.service.bean.CommonNameBean
import com.lv.service.bean.DescribesBean
import com.lv.service.bean.GoodsBean
import com.lv.service.bean.GoodsItemBean
import com.lv.service.bean.ProductBean
import com.lv.service.bean.Sku
import com.lv.service.dialog.ParameterPopupView
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.CollectOrAttentionBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.goods.GoodsDetailsBeans
import com.lv.service.utils.UserUtils
import com.lv.service.utils.YgxAroutPageKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.GoodsAdapter
import com.lv.suyiyong.hfr.adapter.GoodsPagerAdapter
import com.lv.suyiyong.hfr.adapter.GoodsParmasAdapter
import com.lv.suyiyong.hfr.databinding.ActivityGoodsDetailsBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupPosition
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.qcloud.tuikit.tuichat.bean.message.GoodsChatMessageBean
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.lang.reflect.Method


/**
 * 作者： ygx
 * 创建日期：2023/4/1 4:13 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：商品详情页面 issale  0 : 不可买 1：可买
 */
@Route(path = ARoutUtils.GoodsDetilsActivity)
class GoodsDetilsActivity : BaseActivity<ActivityGoodsDetailsBinding>(), OnClickListener {
    @Autowired(name = "spuid")
    @JvmField
    var spuid: String = ""

    private var cpyid: String = ""
    private var ISSALE: String = "0"
    private var mLogo: String = "0"
    private var mBname: String = ""
    private var mAttached: String = "0"
    private var mPhone: String = "0"
    private var mPrice: String = ""
    private var mBatch: Int = 1
    private var loadVp: Int = 0
    private var changeHeight: Int = 0
    private var changeScrollHeight: Int = 0
    private var threshold: Int = 0
    private var mTop1 = 0
    private var mTop2 = 0
    private var mScrollY = 0
    private var isLogin: Boolean = false
    private var mTxAccid: String = ""
    private var mUserInfo: UserInfo? = null
    private var mCompanyCpName: String = ""
    private val mAttachment = GoodsChatMessageBean()
    private var page: Int = 1
    private var pageSize: Int = Constants.pageSize
    private var mBannerData = mutableListOf<String>()
    private var mParmaterData = mutableListOf<CommonNameBean>()
    private var mSkuData = mutableListOf<Sku>()
    private var mViewPagerBeans = mutableListOf<GoodsBean>(
        GoodsBean(0, 0, 0, 0, null, ""),
        GoodsBean(0, 0, 0, 0, null, "")
    )
    private var mBeans = mutableListOf<GoodsItemBean>()
    private var mAdapter: GoodsAdapter? = null
    private var mBanner: Banner<*, *>? = null
    private var mBannerAdapter: BannerImageAdapter<String>? = null

    //    private var mRvDetials: RecyclerView? = null
    private var mLlDetailViews: LinearLayout? = null
    private var mLlCollection: LinearLayout? = null
    private var mLlGuiGe: LinearLayout? = null
    private var mLlFreight: LinearLayout? = null

    //    private var mIvBuyTag: ImageView? = null//放心购
    private var mTvPrice: TextView? = null
    private var mTvSku: TextView? = null
    private var mTvAddress: TextView? = null
    private var mTvName: TextView? = null
    private var mTvWant: TextView? = null
    private var mTvSaleInfo: TextView? = null
    private var mIvCpLogo: ImageView? = null
    private var mTvCpName: TextView? = null
    private var mTvFans: TextView? = null
    private var mTvShop: TextView? = null
    private var mTvPriceDes: TextView? = null
    private var mTvRecomend: TextView? = null
    private var mRvParmas: RecyclerView? = null

    private var mTvGoodsPic: TextView? = null
    private var mClGoodsImg: ConstraintLayout? = null
    private var mYgxIndicator: SlidingTabStrip? = null
    private var mViewPager: ViewPager? = null
    private var mClCompany: ConstraintLayout? = null
    private var mllCollection: LinearLayout? = null
    private var mllGoodsParmas: LinearLayout? = null
    private var mViewSub: View? = null
    private var mTvCollection: TextView? = null
    private var mIvCollection: ImageView? = null
    private var mIvGold: ImageView? = null
//    private var mIvShopTag: ImageView? = null

    private val serviceViewModel: ServiceViewModel by viewModel()
    private var mViewPagerAdapter: GoodsPagerAdapter? = null
    private val mTabs = mutableListOf<String>("店内相似商品", "    店内主推    ")
    private var isCollection = false
    private var mIsGetUser = false//获取过用记信息
    private lateinit var mCheckForGapsMethod: Method
    private lateinit var mMarkItemDecorInsetsDirtyMethod: Method // StaggeredGridLayoutManager
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mIsShow: Boolean = true//标记是否显示，显示时积分定时器才走

    //静止状态
    private val SCROLL_STATE_IDLE = 1

    //拖动或者惯性滑动状态
    private val SCROLL_STATE_SCROLL = 2

    //判断是否是拖动状态
    private var isDragState = false

    private var currentState = SCROLL_STATE_IDLE
    private val paramsMap = mutableMapOf<String, String>()

    override fun getLayoutRes() = R.layout.activity_goods_details
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@GoodsDetilsActivity, clContainer)
            initSingleClickListener(ivBackBlack, ivBackWhite, llSearch)
        }
    }


    override fun initConfig() {
        super.initConfig()
        initAlphaParmas()
        showNoContentView("")
        if (intent != null && spuid.isNullOrEmpty()) {
            spuid = intent.getStringExtra("spuId") ?: ""
        }

        initAdapter()
        lifecycleScope.launchWhenCreated {
            val taskUserInfo = async {
                mUserInfo = getUserInfoForDB()
                isLogin = !mUserInfo?.id.isNullOrEmpty()
            }
            taskUserInfo.await()
            val taskFindOneGoods = async {
                val result = findOneGoods()
                parseFindOneGoodsResult(result)
            }
            taskFindOneGoods.await()
            findGoodsRemark("0")

        }

    }

    private suspend fun getUserInfoForDB(): UserInfo? {
        return withContext(Dispatchers.IO) {
            UserDbHelper.getUserInfo(this@GoodsDetilsActivity)
        }
    }

    private suspend fun findOneGoods(): DataResult<BaseYgxRsp> {
        return withContext(Dispatchers.IO) {
            myScope.async {
                serviceViewModel.findOneGoods(spuid)
            }.await()
        }
    }


    private fun findGoodsRemark(code: String) {
        val findGoodsRemarkMap = mutableMapOf("code" to code, "spuid" to spuid)
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findGoodsRemark(findGoodsRemarkMap) }.await()
            parseFindGoodsRemarkResult(result)

        }
    }

    private fun getRecomendGoods() {
        paramsMap["spuid"] = spuid
        paramsMap["bname"] = mBname
        paramsMap["attached"] = "0"
        findGoodsbotton()
    }

    private fun setHeaderData(it: GoodsDetailsBeans) {
        val images = it.images
        val backdrop = it.backdrop
        val image = it.image ?: ""
//        val stringList = images?.split(",")
        mBannerData.clear()
        if (image.isEmpty()) {//入口图为空
            images?.let {
                mBannerData.addAll(images)
            }
        } else {
            if (!images.isNullOrEmpty() && !images.contains(image)) {
                mBannerData.add(image.urlAddBorder(backdrop, SizeUtils.dp2px(164.0f)))
            }
            images?.forEach { bannerItem ->
                var url = bannerItem
                if (bannerItem == image) {
                    url = bannerItem.urlAddBorder(backdrop, SizeUtils.dp2px(164.0f))
                }
                mBannerData.add(url)
            }
        }

        initBannerAdapter()
        bannerObserver(mBanner)
//        mBannerAdapter?.notifyDataSetChanged()
//        val promiseimage = it.promiseimage
//        mIvBuyTag?.load(promiseimage)
        val price = it.price ?: 0.0
        if (price == 0.0) {
            mTvPrice?.text = "面议"
        } else {
            val priceStr = MoneyUtil.moneydiv("$price", "100")
            mTvPrice?.text = YgxUtilsKt.create19PriceSpanTexts(priceStr)
        }
        mTvName?.text = it.name
        mTvWant?.text = "${it.wantnum}人想要"

        mTvSaleInfo?.visibility = if (ISSALE == "0") View.GONE else View.VISIBLE
        mTvSaleInfo?.text = "${it.batch}件起批"

        mIvCpLogo?.LoadSrc(it.cplogo)
        mCompanyCpName = it.cpname ?: ""
//        mTvCpName?.text = mCompanyCpName
        mTvFans?.text = "粉丝：${it.attentionnum}"
        val describes = it.coordinates
        addViews(describes)
        mTvPriceDes?.text = it.promise
        mBinding.llPhone.visibility = if (ISSALE == "0") View.GONE else View.VISIBLE
        mLlGuiGe?.visibility = if (ISSALE == "0") View.GONE else View.VISIBLE
        mLlFreight?.visibility = if (ISSALE == "0") View.GONE else View.VISIBLE
        mBinding.tvLeftBottom.text = if (ISSALE == "0") "询价" else "加入购物车"
        mBinding.tvRightBottom.text = if (ISSALE == "0") "拨打电话" else "立即购买"
        mIvCollection?.LoadSrc(if (it.status == "0") Constants.GOODS_UNFOCUS_URL else Constants.GOODS_FOCUS_URL)
        isCollection = it.status == "1"
        //0  普通  1 银牌  2 金牌
        val isspecially = it.isspecially
        when (isspecially) {
            "2" -> {
                mClCompany?.setBackgroundResource(com.lv.common.R.drawable.bg_fff0d2_fffbf0_4)
                mTvShop?.setBackgroundResource(com.lv.common.R.drawable.bg_3e_1c_10)
                mTvShop?.setTextColor(Color.parseColor("#FFDC96"))
                mIvGold?.visibility = View.VISIBLE
            }

            else -> {
                mIvGold?.visibility = View.GONE
                mClCompany?.setBackgroundResource(com.lv.common.R.drawable.bg_cir_white_4)
                mTvShop?.setBackgroundResource(com.lv.common.R.drawable.bg_line_theme_15)
                mTvShop?.setTextColor(Color.parseColor("#026DFF"))
            }
        }
//        var drawable: Int = 0
//        when (isspecially) {
//            "1" -> drawable = com.lv.common.R.drawable.icon_renzeng_tag
//            "2" -> drawable = com.lv.common.R.drawable.icon_grold_tag
//            else -> drawable = com.lv.common.R.drawable.icon_nomal_tag
//        }
//
//        val drawableFX = com.lv.common.R.drawable.icon_fx_company_tag
//        val drawableHalf = com.lv.common.R.drawable.icon_half_tag
//        val isopen = it.isopen
//        val ishalf = it.ishalf
//        mTvCpName?.displaySpannableSuperWith3Pic(
//            drawable,
//            mCompanyCpName.filterLine(),
//            drawable2 = if (isopen == "1") drawableFX else -1,
//            drawable3 = if (ishalf == "2") drawableHalf else -1
//        )
        mTvCpName?.text = mCompanyCpName.filterLine()
    }

    private fun initAdapter() {
        mBinding.rvContent.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                //防止第一行到顶部有空白区域  滚动时调用checkForGaps
                val result = mCheckForGapsMethod.invoke(mBinding.rvContent.layoutManager) as Boolean
                //如果发生了重排序 刷新ItemDecoration
                if (result) {
                    mMarkItemDecorInsetsDirtyMethod.invoke(mBinding.rvContent)
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mScrollY += dy
                val layoutManager = mBinding.rvContent.layoutManager as StaggeredGridLayoutManager?
                val startPos = IntArray(layoutManager!!.spanCount)
                layoutManager.findFirstVisibleItemPositions(startPos)
                val position = startPos[0]
                if (position == 0) {
                    val fristView = layoutManager.findViewByPosition(position)
                    val scrollY = -fristView!!.top
                    var alpha = (scrollY - changeHeight) * 1.0f / changeScrollHeight

                    setAlphaTop(alpha)
//                    LogUtils.e("alpha==$alpha")

                }

                if (isDragState) { //拖动状态单独处理不再进行滚动状态监测
                    return
                }
                //滑动时先取消倒计时，设置滑动状态
                scrollCountTimer.cancel()
                if (currentState != SCROLL_STATE_SCROLL) {
//                    setScrollState(SCROLL_STATE_SCROLL);
                }
                scrollCountTimer.start()
            }
        })
        mBinding.rvContent.setOnTouchListener { v, event ->
            //我这里把按下的状态默认为了滚动的状态，当然你也可以分开定义
            isDragState = event?.action == MotionEvent.ACTION_DOWN
            if (isDragState) {
                scrollCountTimer.cancel()
            } else {
                scrollCountTimer.start()
            }
            false
        }
        //反射获取StaggeredGridLayoutManager的checkForGaps方法
        mCheckForGapsMethod =
            StaggeredGridLayoutManager::class.java.getDeclaredMethod("checkForGaps")
        mCheckForGapsMethod.isAccessible = true
        //反射获取RecyclerView的MarkItemDecorInsetsDirty方法
        mMarkItemDecorInsetsDirtyMethod =
            RecyclerView::class.java.getDeclaredMethod("markItemDecorInsetsDirty")
        mMarkItemDecorInsetsDirtyMethod.isAccessible = true
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        mBinding.rvContent.layoutManager = layoutManager
        //防止item乱跳错位 防止item 交换位置
        mBinding.rvContent.itemAnimator = null

        mAdapter = GoodsAdapter(mBeans)
        mBinding.rvContent.adapter = mAdapter
        //设置分隔线
        mBinding.rvContent.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(10.0f),
                SizeUtils.dp2px(10.0f),
                true
            )
        )
        initHeaderView()

//
        val topHeaderTabs: MutableList<String> = mutableListOf<String>("商品", "详情", "推荐")
        mBinding.pstsIndicator.notifyDataSetChanged(topHeaderTabs)



        mBinding.pstsIndicator.setTabClickListener {
            when (it) {
                0 -> mBinding.rvContent.smoothScrollToPosition(0)
                1 -> mBinding.rvContent.smoothScrollBy(0, mTop1 - mScrollY)
                2 -> mBinding.rvContent.smoothScrollBy(0, mTop2 - mScrollY)
            }
        }
        mViewPagerAdapter = GoodsPagerAdapter(this, mViewPagerBeans)
        mViewPager?.adapter = mViewPagerAdapter
        mYgxIndicator?.notifyDataSetChanged(mTabs)
        mViewPager?.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                if (position == 1 && loadVp == 0) {
                    findGoodsRemark("1")
                }
                mYgxIndicator?.currentPosition = position
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        mYgxIndicator?.setTabClickListener { position -> mViewPager?.currentItem = position }


    }

    private fun initHeaderView() {
        val headerView =
            layoutInflater.inflate(R.layout.layout_goods_details_header, null, false)
//        mIvBuyTag = headerView.findViewById<ImageView>(R.id.iv_bug_tag)
        mLlCollection = headerView.findViewById<LinearLayout>(R.id.ll_collection)
        mLlDetailViews = headerView.findViewById<LinearLayout>(R.id.ll_details_views)
//        mRvDetials = headerView.findViewById<RecyclerView>(R.id.rv_detials)
        mLlGuiGe = headerView.findViewById<LinearLayout>(R.id.ll_guige)
        mLlFreight = headerView.findViewById<LinearLayout>(R.id.ll_freight)
        mTvRecomend = headerView.findViewById<TextView>(R.id.tv_recomend_title)
        mTvPrice = headerView.findViewById<TextView>(R.id.tv_price)
        mTvSku = headerView.findViewById<TextView>(R.id.tv_sku)
        mRvParmas = headerView.findViewById<RecyclerView>(R.id.rv_parmas)
        mTvAddress = headerView.findViewById<TextView>(R.id.tv_address)
        mTvName = headerView.findViewById<TextView>(R.id.tv_name)
        mTvWant = headerView.findViewById<TextView>(R.id.tv_want)
        mTvSaleInfo = headerView.findViewById<TextView>(R.id.tv_sale_info)
        mIvCpLogo = headerView.findViewById<ImageView>(R.id.iv_cp_logo)
        mTvCpName = headerView.findViewById<TextView>(R.id.tv_cpname)
        mTvFans = headerView.findViewById<TextView>(R.id.tv_fans)
        mTvShop = headerView.findViewById<TextView>(R.id.tv_shop)
        mTvPriceDes = headerView.findViewById<TextView>(R.id.tv_price_des)
        mTvGoodsPic = headerView.findViewById<TextView>(R.id.tv_goods_pic)
        mClGoodsImg = headerView.findViewById<ConstraintLayout>(R.id.cl_goods_img)
        mClCompany = headerView.findViewById<ConstraintLayout>(R.id.cl_company)
        mYgxIndicator = headerView.findViewById<SlidingTabStrip>(R.id.ygx_indicator)
        mViewPager = headerView.findViewById<ViewPager>(R.id.view_pager)
        mllCollection = headerView.findViewById<LinearLayout>(R.id.ll_collection)
        mTvCollection = headerView.findViewById<TextView>(R.id.tv_collection)
        mIvCollection = headerView.findViewById<ImageView>(R.id.iv_collection)
        mllGoodsParmas = headerView.findViewById<LinearLayout>(R.id.ll_goods_parmas)
        mViewSub = headerView.findViewById<View>(R.id.view_sub)
        mIvGold = headerView.findViewById<ImageView>(R.id.iv_gold)
//        mIvShopTag = headerView.findViewById<ImageView>(R.id.iv_shop_tag)
        mBanner = headerView?.findViewById(R.id.banner) as Banner<*, *>
        mAdapter?.addHeaderView(headerView)
        initHeaderRecycler()
    }

    //设置详情里面的多样式view
    private fun initHeaderRecycler() {
//        mGoodsDetailsHeaderAdapter = GoodsDetailsHeaderAdapter(mGoodsDetailsData)
//        mRvDetials?.adapter = mGoodsDetailsHeaderAdapter
//        val linearLayoutManager: LinearLayoutManager =
//            object : LinearLayoutManager(this) {
//                //禁止竖向滑动 RecyclerView 为垂直状态（VERTICAL）
//                override fun canScrollVertically(): Boolean {
//                    return true
//                }
//            }
//        mRvDetials?.layoutManager = linearLayoutManager
    }


    override fun initData() {
        super.initData()

    }

    private fun findGoodsbotton() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findGoodsbotton(page, pageSize, paramsMap) }
                    .await()
            parseRecommendGoodsResult(result)
        }
    }

    override fun initEvents() {
        super.initEvents()
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                findGoodsbotton()

            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                paramsMap["spuid"] = spuid
                paramsMap["bname"] = mBname
                paramsMap["attached"] = mAttached
                findGoodsbotton()
            }
        })
        mAdapter?.onViewClickListener = OnPositionTListener<GoodsItemBean> { position, item ->
            ARouter.getInstance().build(ARoutUtils.GoodsDetilsActivity)
                .withString("spuid", item.id)
                .navigation()
            finish()
        }
        mClCompany?.setSafeListener {
//            ARouter.getInstance().build(ARoutUtils.CompanyInfoActivity)
//                .withString("cpyid", cpyid)
//                .navigation()
        }
        mllCollection?.setSafeListener {
            if (isLogin) {
                collectOrAttention(spuid)
            } else {
                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
            }
        }
        initSingleClickListener(
            mllGoodsParmas,
            mRvParmas,
            mBinding.tvLeftBottom,
            mBinding.tvRightBottom,
            mBinding.llPhone,
            mBinding.llSearch,
            mBinding.llService,
            mBinding.llShop,
            mBinding.ivShareBlack,
            mBinding.ivShareWhite
        )

        mViewPagerAdapter?.onViewClickListener = OnPositionTListener { position, data ->
            ARouter.getInstance().build(ARoutUtils.GoodsDetilsActivity)
                .withString("spuid", data.id)
                .navigation()
            finish()
        }

    }

    //收藏商品
    private fun collectOrAttention(spuid: String) {
        val body = CollectOrAttentionBody("1", spuid)
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.collectOrAttention(body) }.await()
            parseCollectGoodsResult(result)
        }
    }

    private fun initAlphaParmas() {
        threshold = SizeUtils.dp2px(360.0f)
        changeHeight = StatusBarUtil.getStatusBarHeight(this) + SizeUtils.dp2px(42.0f)
        changeScrollHeight = threshold - changeHeight
        setAlphaTop(0f)

    }

    private fun setAlphaTop(alphas: Float) {
        var alpha = alphas
        if (alpha < 0) {
            alpha = 0f
        }
        if (alpha > 1) {
            alpha = 1f
        }
        mBinding.ivBackBlack.alpha = alpha
        mBinding.pstsIndicator.alpha = alpha
        mBinding.ivCatBlack.alpha = alpha
        mBinding.ivShareBlack.alpha = alpha
        mBinding.llSearch.alpha = alpha
        mBinding.viewSub.alpha = alpha
        mBinding.pstsIndicator.visibility = if (alpha == 0.0f) View.GONE else View.VISIBLE
        alpha = 1 - alphas
        if (alpha < 0) {
            alpha = 0f
        }
        mBinding.ivBackWhite.alpha = alpha
        mBinding.ivCatWhite.alpha = alpha
        mBinding.ivShareWhite.alpha = alpha
    }

    //这里采用100ms来判断是否已经是静止状态，100ms结束后证明是静止状态
    private val scrollCountTimer: CountDownTimer = object : CountDownTimer(100, 1) {
        override fun onTick(millisUntilFinished: Long) {}
        override fun onFinish() {
            if (mTvRecomend == null || mLlDetailViews == null) {
                return
            }
            mClGoodsImg?.apply {
                mTop1 = top - changeHeight - SizeUtils.dp2px(37.0f)

            }
            mTvRecomend?.apply {
                mTop2 = top - changeHeight - SizeUtils.dp2px(37.0f)

            }
//            LogUtils.e(
//                "mScrollY==$mScrollY",
//                "mLlDetailViews==${mLlDetailViews?.top}",
//                "changeHeight==$changeHeight",
//                "mTop1=$mTop1===mTop2==$mTop2==="
//            )
            if (mScrollY < mTop1) {
                mBinding.pstsIndicator.currentPosition = 0
            } else if (mScrollY < mTop2) {
                mBinding.pstsIndicator.currentPosition = 1
            } else {  //在【宝贝】区域中，顶部栏中的【宝贝】被标记
                mBinding.pstsIndicator.currentPosition = 2
            }
        }
    }

    //    动态添加商品详情图片
    private fun addViews(stringList: List<DescribesBean>?) {
        mLlDetailViews?.removeAllViews()
        if (stringList.isNullOrEmpty()) {
            mLlDetailViews?.visibility = View.GONE
            return
        }
        mLlDetailViews?.visibility = View.VISIBLE
        var mRlParent: RelativeLayout
        stringList.forEach { item ->
            mRlParent = RelativeLayout(this)
            mRlParent.removeAllViews()
            when (item.type) {
                "0" -> {//可点击的图
                    val imageView = ImageView(this)
                    val layoutParams: FrameLayout.LayoutParams = FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(52.0f)
                    imageView.layoutParams = layoutParams
                    imageView.adjustViewBounds = true
                    Glide.with(this).load(item.image).into(imageView)
                    mRlParent.addView(imageView)
                }

                "1" -> {//不可点击的图
                    val imageView = ImageView(this)
                    val layoutParams: FrameLayout.LayoutParams = FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(52.0f)
                    imageView.layoutParams = layoutParams
                    imageView.adjustViewBounds = true
                    Glide.with(this).load(item.image).into(imageView)
                    mRlParent.addView(imageView)
                }
//                "2" -> {//视频
//
//                }
                "3" -> {//文字
                    val textView = TextView(this)
                    val layoutParams: FrameLayout.LayoutParams = FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT
                    )
                    layoutParams.width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(52.0f)
                    textView.layoutParams = layoutParams
                    textView.text = item.image
                    textView.setTextColor(Color.parseColor("#242424"))
                    textView.textSize = 13.0f
                    mRlParent.addView(textView)
                }

            }
            val product = item.product
            setClickViews(product, mRlParent)
            mLlDetailViews?.addView(mRlParent)

        }
    }

    /**
     * 添加点击的view
     */
    private fun setClickViews(
        product: List<ProductBean>?,
        mRlParent: RelativeLayout
    ) {
        product?.forEach { itemChick ->
            val mViewClick = View(this)
            mRlParent.addView(mViewClick)
            val aDoubleX: Float = itemChick.x.toInt() * 1.0f / 3
            val aDoubleXX: Float = itemChick.w.toInt() * 1.0f / 3
            val aDoubleY: Float = itemChick.y.toInt() * 1.0f / 3
            val aDoubleYY: Float = itemChick.h.toInt() * 1.0f / 3
            val clickParams = mViewClick.layoutParams as RelativeLayout.LayoutParams
            clickParams.leftMargin = SizeUtils.dp2px(aDoubleX)
            clickParams.topMargin = SizeUtils.dp2px(aDoubleY)
            clickParams.width = SizeUtils.dp2px(aDoubleXX)
            clickParams.height = SizeUtils.dp2px(aDoubleYY)
            mViewClick.layoutParams = clickParams
            mViewClick.setSafeListener {
                YgxAroutPageKt.arout2page(
                    this,
                    "3",
                    itemChick.spuid,
                    type = itemChick.type,
                    user = mUserInfo, adId = -1
                )
            }
            if (Constants.isShowPicAlpha) {
                mViewClick.setBackgroundColor(Color.parseColor("#00CC90"))
                mViewClick.alpha = 0.3f
            }
        }
    }

    /**
     * 设置Banner适配器
     */
    private fun bannerObserver(banner: Banner<*, *>?) {
        mBanner?.addBannerLifecycleObserver(viewLifeCycleOwner) //添加生命周期观察者
            ?.setAdapter(mBannerAdapter)
            ?.setIntercept(false)?.indicator = CircleIndicator(this)
        mBannerAdapter?.setOnBannerListener { data, position ->
            YgxAroutPageKt.scanMediaPic(mBannerData, position)
        }

    }


    private fun parseFindOneGoodsResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<GoodsDetailsBeans> { code, data, message, result ->
                data?.let {
                    cpyid = it.cpyid ?: ""
//                    ISSALE = it.issale ?: "0"
                    ISSALE = "0"
                    mLogo = it.image ?: ""
                    mBname = it.secname ?: ""
                    mPrice = MoneyUtil.moneydiv("${it.price}", "100").priceSmallDot()
                    mBatch = it.batch ?: 1
                    val contract = it.contract
                    if (!contract.isNullOrEmpty()) {
                        mPhone = contract[0].tel ?: ""
                    }
//                    mAttachment.id = it.id
                    mAttachment.spuId = it.id
                    mAttachment.spuCount = "1"
                    val url = it.image?.urlAddBorder(it.backdrop, SizeUtils.dp2px(69.0f), 80)
                    mAttachment.spuIcon = url
                    mAttachment.spuName = it.name
                    mAttachment.spuPrice = mPrice
                    mTxAccid = it.txaccid ?: ""
                    if (it.islisted == "0") {
                        mBinding.tvOut.visibility = View.VISIBLE
                        mBinding.tvRightBottom.isEnabled = false
                        mBinding.tvLeftBottom.isEnabled = false
                        mBinding.tvLeftBottom.alpha = 0.2f
                        mBinding.tvRightBottom.alpha = 0.2f
                    } else {
                        mBinding.tvOut.visibility = View.GONE
                        mBinding.tvRightBottom.isEnabled = true
                        mBinding.tvLeftBottom.isEnabled = true
                    }
                    setHeaderData(it)
                    val attribute = it.attribute
                    mParmaterData.clear()
                    attribute?.forEach { att ->
                        mParmaterData.add(
                            CommonNameBean(
                                att.name ?: "",
                                att.value ?: ""
                            )
                        )
                    }
                    val skuList = it.skuList
                    skuList?.let { sku ->
                        mSkuData.clear()
                        mSkuData.addAll(sku)
                        mTvSku?.text = "${skuList.size}种规格可选"
                    }
                    mTvAddress?.text = "${it.province}${it.city}"
                    val parmasData = mutableListOf<CommonNameBean>()
                    parmasData.clear()
                    if (mParmaterData.size > 4) {
                        val subList = mParmaterData.subList(0, 4)
                        parmasData.addAll(subList)
                    } else {
                        parmasData.addAll(mParmaterData)
                    }
                    val mParamsAapter = GoodsParmasAdapter(parmasData)
                    mRvParmas?.adapter = mParamsAapter
                    mParamsAapter.mOnViewItemClickListener = OnPositionTListener { position, data ->
                        showBottomDialog()
                    }
                    if (parmasData.isEmpty()) {
                        mllGoodsParmas?.visibility = View.GONE
                        mViewSub?.visibility = View.VISIBLE
                    } else {
                        mllGoodsParmas?.visibility = View.VISIBLE
                        mViewSub?.visibility = View.GONE
                    }
                    getRecomendGoods()


                }

            }
            onBizError<GoodsDetailsBeans> { code, message, data ->
                if (code == "205") {
                    mAdapter?.removeAllHeaderView()
                    mAdapter?.notifyDataSetChanged()
                    val headerView =
                        layoutInflater.inflate(
                            R.layout.layout_goods_details_delete_header, null, false
                        )
                    headerView?.findViewById<ImageView>(R.id.iv_image)?.LoadSrc(Constants.EMPTY_URL)
                    mAdapter?.addHeaderView(headerView)
                    StatusBarUtil.setHeightAndPadding(this@GoodsDetilsActivity, mBinding.titleBar)
                    mBinding.titleBar.visibility = View.VISIBLE
                    mBinding.clFloat.visibility = View.GONE
                    mBinding.titleBar.setTitle("商品过期不存在")
                    mBinding.titleBar.onClickBackIcon { finish() }
                    val layoutParams =
                        mBinding.refreshLayout.layoutParams as ConstraintLayout.LayoutParams
                    layoutParams.bottomMargin = 0
                    getRecomendGoods()
                } else {
                    showToast(message)
                }
            }
        }
        data.onFailure {
            showLoadErrorView()
        }
    }

    private fun parseRecommendGoodsResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<GoodsBean> { code, data, message, result ->
                data?.let {
                    val items = it.items
                    mAttached = it.attached ?: ""
                    MyUtils.recyclerviewSetData(
                        page, pageSize, mBinding.refreshLayout, mBeans, items, mAdapter
                    )
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.finishLoadMore()
            }
        }
        data.onFailure {
            mBinding.refreshLayout.finishRefresh()
            mBinding.refreshLayout.finishLoadMore()
        }
    }

    private fun parseFindGoodsRemarkResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<GoodsBean> { code, data, message, result ->
                data?.let {
                    if (mViewPager?.currentItem == 0) {
                        mViewPagerBeans.removeAt(0)
                        mViewPagerBeans.add(0, it)
                    } else {
                        loadVp++
                        mViewPagerBeans.removeAt(1)
                        mViewPagerBeans.add(it)
                    }
                    mViewPagerAdapter?.setDatas(mViewPagerBeans)
                }

            }
            onBizError<GoodsBean> { code, message, data ->
                showToast(message)
            }
        }
    }

    private fun parseCollectGoodsResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (message == "收藏成功") {
                    mIvCollection?.LoadSrc(Constants.GOODS_FOCUS_URL)
                    isCollection = true
                } else {
                    isCollection = false
                    mIvCollection?.LoadSrc(Constants.GOODS_FOCUS_URL)
                }
                showToast(message.toString())

            }
            onBizError<GoodsBean> { code, message, data ->
                showToast(message)
            }
        }
    }


    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
        mBannerAdapter = object : BannerImageAdapter<String>(mBannerData) {
            override fun onBindView(
                holder: BannerImageHolder?,
                data: String?,
                position: Int,
                size: Int
            ) {
                Glide.with(this@GoodsDetilsActivity)
                    .load(data)
                    .into(holder?.imageView!!)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back_black, R.id.iv_back_white -> finish()
            R.id.ll_goods_parmas, R.id.rv_parmas -> showBottomDialog()
            R.id.tv_left_bottom -> {
                if (isLogin) {
                    if (ISSALE == "1") {
                        showCatBottomDialog("0")
                    } else {//询价 带商品信息到聊天面板
                        chatSendGoodsInfo(0)
                    }
                } else {
                    ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
                }
            }
//            R.id.tv_right_bottom -> {
//                if (isLogin) {
//                    if (ISSALE == "1") {
//                        showCatBottomDialog("1")
//                    } else {//拨打电话
//                        YgxUtilsKt.callPhone(this, mPhone)
//                    }
//                } else {
//                    ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
//                }
//            }
            R.id.ll_phone, R.id.tv_right_bottom -> {
                YgxUtilsKt.callPhone(this, mPhone)
                savewantnum()
                savecallnum()
                sendCallMessage(mPhone)
            }

            R.id.ll_search -> ARouter.getInstance().build(ARoutUtils.HomeSearchActivity)
                .withString("searchCode", "3")
                .navigation()

            R.id.iv_cat_black -> ARouter.getInstance().build(ARoutUtils.HomeActivityURL)
                .withInt("TabId", 3).navigation()

            R.id.iv_cat_white -> ARouter.getInstance().build(ARoutUtils.HomeActivityURL)
                .withInt("TabId", 3).navigation()

            R.id.ll_service -> chatSendGoodsInfo(1)//客服
            R.id.ll_shop -> {
//                ARouter.getInstance().build(ARoutUtils.CompanyInfoActivity)
//                    .withString("cpyid", cpyid)
//                    .navigation()
            }

            R.id.iv_share_black, R.id.iv_share_white -> {
//                YgxManager.showDialogShare(
//                    this,
//                    mAttachment.spuName,
//                    mCompanyCpName,
//                    "${Constants.KEY_SHARE_HEADER_SYY}${Constants.KEY_SHARE_GOODS}${mGoodsDatasBean?.id}",
//                    mAttachment.spuIcon, -1, OnPositionListener {
//
//                    }
//                )
            }

        }
    }

    /**
     * type 0 询价 带商品信息聊天 1 直接聊天
     */
    private fun chatSendGoodsInfo(type: Int) {
        if (isLogin) {
            if (type == 0) {
                mAttachment.apns = "商品信息"
                UserUtils.showChatActivity(mTxAccid, mCompanyCpName, mAttachment)
            } else {
                UserUtils.showChatActivity(mTxAccid, mCompanyCpName)
            }
            savewantnum()
            savecallnum()
        } else {
            ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()
        }

    }

    private fun savewantnum() {
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { viewModel.savewantnum(spuid) }.await()
//        }
    }

    private fun savecallnum() {
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { serviceViewModel.savecallnum(cpyid) }.await()
//
//        }
    }

    private fun sendCallMessage(mPhone: String) {
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { serviceViewModel.sendCallMessage(mPhone) }.await()
//        }
    }

    private fun showBottomDialog() {
        val popupView =
            ParameterPopupView(this, mParmaterData)
        XPopup.Builder(this)
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个
            .popupPosition(PopupPosition.Bottom)
            .asCustom(popupView)
            .show()
    }

    /**
     * type 0:加入购物车 1：立即购买
     */
    private fun showCatBottomDialog(type: String) {
        var mCartDialog: BasePopupView? = null
//        val popupView =
//            CatGoodsPopupView(
//                this, type, mLogo, mPrice, mBatch, mSkuData,
//                OnPositionTListener { count, data ->
//                    startLoading()
//                    if (type == "0") {
//                        if (count > 0) {
//                            val trolleySkus = mutableListOf<TrolleySkusBody>()
//                            trolleySkus.clear()
//                            for (i in data.indices) {
//                                val saleGoodsnum = data[i].saleGoodsnum
//                                if (saleGoodsnum > 0) {
//                                    val trolleySkusBody =
//                                        TrolleySkusBody(data[i].id!!, saleGoodsnum)
//                                    trolleySkus.add(trolleySkusBody)
//                                }
//                            }
//                            val addTrolleyReqBody = AddTrolleyReqBody(cpyid, spuid, trolleySkus)
//                            lifecycleScope.launchWhenCreated {
//                                val result: DataResult<BaseYgxRsp> =
//                                    myScope.async { viewModel.addTrolley(addTrolleyReqBody) }
//                                        .await()
//                                parseAddTrolleyResult(result)
//                            }
//                        }
//                    }
//                    mCartDialog?.dismiss()
//                }
//            )
//        mCartDialog = XPopup.Builder(this)
//            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个
//            .popupPosition(PopupPosition.Bottom)
//            .asCustom(popupView)
//        mCartDialog?.show()
    }

    private fun parseAddTrolleyResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            loadFinished()
            onBizOK<String> { code, data, message, result ->
                message?.let { it1 ->
                    showToast(it1)
                }

            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
        data.onFailure {
            loadFinished()
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
    }

    private fun exitPage() {
        val intent = intent
        intent?.putExtra("state", isCollection)
        setResult(RESULT_OK, intent)
        finish()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        exitPage()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitPage()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }
}